package models

import (
	"time"
)

// Payment 结构体表示支付信息
type Payment struct {
	ID            int       `json:"id"`
	OrderID       int       `json:"order_id"`
	PaymentMethod string    `json:"payment_method"`
	PaymentStatus string    `json:"payment_status"`
	PaymentDate   time.Time `json:"payment_date"`
	Amount        float64   `json:"amount"`
}

// 获取指定订单ID的支付信息
func GetPaymentByOrderID(orderID int) (Payment, error) {
	var payment Payment
	err := db.QueryRow("SELECT id, order_id, payment_method, payment_status, payment_date, amount FROM payments WHERE order_id = ?", orderID).
		Scan(&payment.ID, &payment.OrderID, &payment.PaymentMethod, &payment.PaymentStatus, &payment.PaymentDate, &payment.Amount)
	if err != nil {
		return payment, err
	}
	return payment, nil
}

// 创建支付信息
func AddPayment(p Payment) (int64, error) {
	stmt, err := db.Prepare("INSERT INTO payments(order_id, payment_method, payment_status, payment_date, amount) VALUES(?, ?, ?, ?, ?)")
	if err != nil {
		return 0, err
	}
	defer stmt.Close()

	result, err := stmt.Exec(p.OrderID, p.PaymentMethod, p.PaymentStatus, p.PaymentDate, p.Amount)
	if err != nil {
		return 0, err
	}

	return result.LastInsertId()
}

// 更新支付状态
func UpdatePaymentStatus(paymentID int, status string) error {
	stmt, err := db.Prepare("UPDATE payments SET payment_status = ? WHERE id = ?")
	if err != nil {
		return err
	}
	defer stmt.Close()

	_, err = stmt.Exec(status, paymentID)
	return err
}
